package service

import (
	"cloud-stm32-cld-platform/config"
	"cloud-stm32-cld-platform/cons"
	"cloud-stm32-cld-platform/model"
	"context"
	"os/exec"

	"github.com/sirupsen/logrus"
)

type ExecSvc struct {
	*model.FileModel
}

func NewExecSvc(mdl *model.FileModel) *ExecSvc {
	return &ExecSvc{mdl}
}

func (es *ExecSvc) UnzipPrj(ctx context.Context) error {
	return es.Execute(model.UnZip, ctx)
}

func (es *ExecSvc) CompileAndLink(ctx context.Context) error {
	return es.Execute(model.Build, ctx)
}

func (es *ExecSvc) ChipBurning(ctx context.Context) error {
	return es.Execute(model.Download, ctx)
}

func (es *ExecSvc) Execute(mode model.FileCmdMode, ctx context.Context) (err error) {
	switch mode {
	case model.Build:
		fallthrough
	case model.Download:
		err = execute(es.KeilFileModel, mode, ctx)
	case model.UnZip:
		err = execute(es.UnzipFileModel, mode, ctx)
	}
	return
}

func execute(fm model.FileModelInterface, mode model.FileCmdMode, ctx context.Context) error {
	exe_paras := fm.Paras()
	logger := config.GlobalConfigCenter.Gets([]string{cons.DefCnfKey_LOGGER})[0].(*logrus.Logger)
	logger.Infof("Execute Cmd: %v", exe_paras)

	cmd := exec.Command(fm.GetCmd(), exe_paras...)
	out, err := cmd.CombinedOutput()
	if err != nil {
		logger.Infof("Execute Cmd: %d Failed, Message: %s", mode, out)
		return err
	}
	return nil
}
